package com.freshfresh.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.freshfresh.activity.R;
import com.freshfresh.utils.ImageLoadOptions;
import com.freshfresh.view.db.DBManager;
import com.hangyjx.widget.dialog.CustomDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
//本地购物车 

public class ShopLocalAdapter extends BaseAdapter {
	List<Map<String,Object>> apk_list;
	LayoutInflater inflater;
	Context context;
	TextView textvieww;
	TextView textview;
	TextView textview0;
	public ShopLocalAdapter(Context context, List<Map<String,Object>> apk_list,TextView textvieww,TextView textview,TextView textview0) {
		this.context=context;
		this.textvieww=textvieww;
		this.textview=textview;
		this.textview0=textview0;
		this.apk_list = apk_list;
		this.inflater = LayoutInflater.from(context);
	}
	public void onDateChange(List<Map<String,Object>> apk_list) {
		this.apk_list = apk_list;
		this.notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return apk_list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return apk_list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final Map<String,Object> entity = apk_list.get(position);
		final ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.it_shoppingcar, null);
			holder.iv_it_shoppingcar = (ImageView) convertView
					.findViewById(R.id.iv_it_shoppingcar);
			
			holder.tv_it_shoppingcar_del = (ImageView) convertView
					.findViewById(R.id.tv_it_shoppingcar_del);
			
			holder.tv_it_shoppingcar_title = (TextView) convertView
					.findViewById(R.id.tv_it_shoppingcar_title);
			
			
			holder.tv_it_shoppingcar_increase = (TextView) convertView
			.findViewById(R.id.tv_it_shoppingcar_increase);
			holder.tv_it_shoppingcar_decrease = (TextView) convertView
					.findViewById(R.id.tv_it_shoppingcar_decrease);
			
			holder.tv_it_shoppingcar_stock = (TextView) convertView
					.findViewById(R.id.tv_it_shoppingcar_stock);
			holder.tv_it_shoppingcar_price = (TextView) convertView
					.findViewById(R.id.tv_it_shoppingcar_price);
			holder.ed_it_shoppingcar_count = (TextView) convertView
					.findViewById(R.id.ed_it_shoppingcar_count);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
		if(entity.get("picurl")!=null){
			ImageLoader.getInstance().displayImage(entity.get("picurl").toString(), holder.iv_it_shoppingcar, ImageLoadOptions.getOptions(0));
			}
		holder.tv_it_shoppingcar_title.setText(entity.get("name").toString());
		holder.tv_it_shoppingcar_stock.setText(entity.get("stock").toString());
		holder.tv_it_shoppingcar_price.setText("¥"+entity.get("price").toString());
		holder.ed_it_shoppingcar_count.setText(entity.get("count").toString());
		
		holder.tv_it_shoppingcar_del.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				operateDialog(context, entity.get("product_id").toString(),"温馨提示", "确认删除这件商品吗？", "确定", "取消");
				
				
			}
		});
		//加
		holder.tv_it_shoppingcar_increase.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				int mycount=1;
				mycount=Integer.parseInt(holder.ed_it_shoppingcar_count.getText().toString());
				mycount++;
				holder.ed_it_shoppingcar_count.setText(mycount+"");
				
				UpdateShopCar(entity.get("product_id").toString(),entity.get("picurl").toString(), entity.get("name").toString(), entity.get("stock").toString(), entity.get("price").toString(), holder.ed_it_shoppingcar_count.getText().toString());
				
				
			}
		});
		holder.tv_it_shoppingcar_decrease.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				int mycount=1;
				mycount=Integer.parseInt(holder.ed_it_shoppingcar_count.getText().toString());
				mycount--;
				if(mycount<1){
					mycount=1;
					Toast.makeText(context, "该商品至少购买一件", 0).show();
				}
				holder.ed_it_shoppingcar_count.setText(mycount+"");
				UpdateShopCar(entity.get("product_id").toString(),entity.get("picurl").toString(), entity.get("name").toString(), entity.get("stock").toString(), entity.get("price").toString(), holder.ed_it_shoppingcar_count.getText().toString());
			}
		});
		return convertView;
	}
	
	class ViewHolder {
		ImageView iv_it_shoppingcar;//图片
		ImageView tv_it_shoppingcar_del;//删除
		TextView tv_it_shoppingcar_title;//名称 
		TextView tv_it_shoppingcar_stock;//库存
		TextView tv_it_shoppingcar_price;//价格
		TextView ed_it_shoppingcar_count;//数量
		
		TextView tv_it_shoppingcar_increase;//加
		TextView tv_it_shoppingcar_decrease;//减
	}
	
	public Cursor getAllPersonInfo() {
		return DBManager.getDBconnection(context).query("fresh_shoppingcar", new String[] { "product_id","picurl", "name", "stock","price","count" }, null, null, null, null, null);
	}
	public List<Map<String,Object>> queryAllLocal(){
		final List<Map<String,Object>> listmaps=new ArrayList<Map<String,Object>>();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				Cursor cursor=getAllPersonInfo();
				int totalprice=0;
				int totalcount=0;
				 if (cursor.moveToFirst() == true)  
		         {  
		             String str = "";  
		               
		             for (int index=0; index<cursor.getCount(); index++)  
		             {  
		            	 Map<String,Object> map=new HashMap<String, Object>();
		            	 String product_id = cursor.getString(cursor.getColumnIndex("product_id"));  
		                 String picurl = cursor.getString(cursor.getColumnIndex("picurl"));  
		                 String name = cursor.getString(cursor.getColumnIndex("name"));  
		                 String stock = cursor.getString(cursor.getColumnIndex("stock"));  
		                 String price = cursor.getString(cursor.getColumnIndex("price"));  
		                 String count = cursor.getString(cursor.getColumnIndex("count"));  
		                 map.put("product_id", product_id);
		                 map.put("picurl", picurl);
		                 map.put("name", name);
		                 map.put("stock", stock);
		                 map.put("price", price);
		                 map.put("count", count);
		                 listmaps.add(map);
		                 
		                 //计算价格 数量*单价
//		                 float count=Float.parseS(count);
		                 float mycount=Float.parseFloat(count);
		                 float myprice=Float.parseFloat(price);
		                 totalprice+=mycount*myprice;
		                 totalcount+=mycount;
		                 cursor.moveToNext();  
		             }  
		             cursor.close();  
		             Log.e("totalprice是多少………………", totalprice+"");
//		             textview.setText("总计： ¥"+totalprice+"");
//		             textview0.setText("总计： ¥"+totalprice+"");
		         }  
		         else  
		         {  
		        	 totalprice=0;
//		        	 textview.setText("总计： ¥"+"0");
//		        	 textview0.setText("总计： ¥"+"0");
		         }  
				 Message msg=Message.obtain();
				 Bundle bundle=new Bundle();
				 bundle.putString("totalprice", totalprice+"");
				 bundle.putString("count", totalcount+"");
				 msg.setData(bundle);
				 msg.what=0;
				 handler.sendMessage(msg);
			}
		}).start();
		
		return listmaps;	
	}
	
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				textview.setText("总计： ¥"+msg.getData().getString("totalprice"));
	             textview0.setText("总计： ¥"+msg.getData().getString("totalprice"));
	             textvieww.setText("共"+msg.getData().getString("count")+"件商品");
				break;

			default:
				break;
			}
		};
	};
	//数据库条件删除方法
		 public void DeleteUserPhoto(String name){
		        SQLiteDatabase db =DBManager.getDBconnection(context);
		        String[] args = {String.valueOf(name)};
		        db.delete("fresh_shoppingcar", "product_id=?", args);
		        
		        final List<Map<String,Object>> listmaps=new ArrayList<Map<String,Object>>();
						
						Cursor cursor=getAllPersonInfo();
						int totalprice=0;
						int totalcount=0;
						 if (cursor.moveToFirst() == true)  
				         {  
				             String str = "";  
				               
				             for (int index=0; index<cursor.getCount(); index++)  
				             {  
				            	 Map<String,Object> map=new HashMap<String, Object>();
				            	 String product_id = cursor.getString(cursor.getColumnIndex("product_id"));  
				                 String picurl = cursor.getString(cursor.getColumnIndex("picurl"));  
				                 String names = cursor.getString(cursor.getColumnIndex("name"));  
				                 String stock = cursor.getString(cursor.getColumnIndex("stock"));  
				                 String price = cursor.getString(cursor.getColumnIndex("price"));  
				                 String count = cursor.getString(cursor.getColumnIndex("count"));  
				                 map.put("product_id", product_id);
				                 map.put("picurl", picurl);
				                 map.put("name", names);
				                 map.put("stock", stock);
				                 map.put("price", price);
				                 map.put("count", count);
				                 listmaps.add(map);
				                 
				                 //计算价格 数量*单价
//				                 float count=Float.parseS(count);
				                 float mycount=Float.parseFloat(count);
				                 float myprice=Float.parseFloat(price);
				                 totalprice+=mycount*myprice;
				                 totalcount+=mycount;
				                 cursor.moveToNext();  
				             }  
				             cursor.close();  
				             Log.e("totalprice是多少………………", totalprice+"");
				             textview.setText("总计： ¥"+totalprice+"");
				             textview0.setText("总计： ¥"+totalprice+"");
				             textvieww.setText("共"+totalcount+"件商品");
				         }  
				         else  
				         {  
				        	 totalprice=0;
				        	 textview.setText("总计： ¥"+"0");
				        	 textview0.setText("总计： ¥"+"0");
				        	 textvieww.setText("共0件商品");
				         }  
				
				onDateChange(listmaps);
		    }
	//dialog
			public  void operateDialog(Context context,final String phone,String title,String message,
					String positiveButtonText,String negativeButtonText){
				CustomDialog.Builder builder = new CustomDialog.Builder(context);
				builder.setTitle(title);
				builder.setMessage(message);
				//确定按钮
				builder.setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						DeleteUserPhoto(phone);
						dialog.dismiss();
					}
				});
				//取消按钮
				builder.setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				builder.createB2().show();
			}
			//本地购物车加减的时候更新数据库
			 public int UpdateShopCar(String product_id,String picurl,String name,String stock,String price, String count){
			        SQLiteDatabase db =DBManager.getDBconnection(context);
			        ContentValues cv = new ContentValues();
			        cv.put("product_id", product_id);
			        cv.put("picurl", picurl);
			        cv.put("name", name);
			        cv.put("stock", stock);
			        cv.put("price", price);
			        cv.put("count", count);
			        String[] args = {String.valueOf(name)};
			        queryAllLocal();
			        
			        return db.update("fresh_shoppingcar", cv, "name=?",args);    
			    }
			 
			 
			 
			 
}
